<template>
    <!-- 弹窗组件 -->
    <div class="dialog-box">
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="900">
            <el-form :model="formData" :rules="rules" ref="formRef">
                <el-row :gutter="20">

                    <el-col :span="12">
                        <el-form-item label="调入仓库" prop="to_warehouse_name">
                            <el-input readonly @click="ShowClick('1')" v-model="formData.to_warehouse_name"
                                suffix-icon="MoreFilled" placeholder="请选择" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="调拨日期" prop="transfer_date">
                            <el-date-picker value-format="YYYY-MM-DD" v-model="formData.transfer_date" type="date"
                                placeholder="请选择" style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="note">
                            <el-input type="textarea" rows="4" v-model="formData.note" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div style="margin: 20px 0 10px 0; font-weight: bold;" class="flex_bw_center">
                <div class="section-title">调拨产品</div>
                <div>
                    <el-button type="primary" color="#626aef" @click="dbcpOpen">
                        选择产品
                    </el-button>
                </div>
            </div>
            <el-table :data="productList" border style="width: 100%;">
                <el-table-column prop="name" label="产品名称">
                    <template #default="scope">
                        <span>{{ scope.row?.name || scope.row?.product_name }}</span>

                    </template>
                </el-table-column>
                <el-table-column prop="specification" label="规格型号" />
                <el-table-column prop="unit" label="单位" />
                <el-table-column prop="stock_num" label="库存数量" />
                <el-table-column prop="transfer_num" label="调拨数量">
                    <template #default="scope">
                        <el-input v-model="scope.row.transfer_num" size="small" type="number" />
                    </template>
                </el-table-column>
                <el-table-column prop="role" label="备注">
                    <template #default="scope">
                        <el-input v-model="scope.row.note" size="small" />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                    <template #default="scope">
                        <el-button type="danger" link @click="removeProduct(scope.$index)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" color="#626aef" @click="submitForm">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <StorageWarehouseDialog v-model:dialogVisible="showWarehouseDialog" :warehouses="warehouseList"
            @confirm="onWarehouseSelect" />
        <!-- 选择产品 -->
        <SelectProductDialog :selecList="selecList" v-model:dialogVisible="showProductDialog"
            :warehouses="warehouseList" v-model:modelValue="selectedProducts" @confirm="onProductConfirm" />
    </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import api from "@/api";
import StorageWarehouseDialog from "../StorageWarehouseDialog.vue";
import SelectProductDialog from "../SelectProductDialog.vue";

// 定义产品类型
interface Product {
    id: string | number;
    name: string;
    no: string;
    code?: string | number; // 添加可选的code字段以兼容SelectProductDialog
    specification: string;
    unit: string;
    stock_num: number | string;
    transfer_num: number | string;
    warehouse_id: string;
    warehouse_name: string;
    remark: string;
    [key: string]: any;
}

// 接收父组件传入的值
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    dialogType: {
        type: String,
        default: 'add'
    },
    dialogRow: {
        type: Object,
        default: () => ({})
    }
});


let showWarehouseDialog = ref(false);

const selectedProducts = ref<any[]>([]);


interface list {
    id: string | number;
    product: {
        name: string;
        no: string;
        specification: string;
        unit: string;
    };
    stock_num: number;
    warehouse_id: string;
    warehouse_name: string;
    remark: string;
  
}
//选中的产品
let selecList = ref<any[]>([]);
function onProductConfirm(list: list[]) {
    console.log(list,'list');
    

    if(   productList.value.length == 0){
      
        productList.value = list.map(item => ({
            id: item.id,
            name: item.product.name,
            no: item.product.no,
            specification: item.product.specification,
            unit: item.product.unit || '个',
            stock_num: item.stock_num || 0,
            transfer_num: '',
            warehouse_id: item.warehouse_id,
            warehouse_name: getWarehouseName(item.warehouse_id),
            remark: ''
        }));
    }else{
        let selecList = list.map(item => ({
            id: item.id,
            name: item.product.name,
            no: item.product.no,
            specification: item.product.specification,
            unit: item.product.unit || '个',
            stock_num: item.stock_num || 0,
            transfer_num: '',
            warehouse_id: item.warehouse_id,
            warehouse_name: getWarehouseName(item.warehouse_id),
            remark: ''
        }));
     

        let pushData = selecList.filter((item)=> !productList.value.some(p => p.product_no === item.no)) || []
        productList.value = [...productList.value, ...pushData]
        console.log(productList.value,'pushData');
    }



}

// 获取仓库名称
function getWarehouseName(warehouseId: string) {
    if (!warehouseId || !warehouseList.value || warehouseList.value.length === 0) {
        return '未知仓库';
    }
    const warehouse = warehouseList.value.find((w: any) => String(w.id) === String(warehouseId));
    console.log(warehouse, 'warehouse');
    return warehouse ? warehouse.name : '未知仓库';
}

let showProductDialog = ref(false);

watch(() => showProductDialog.value, (val) => {
    console.log(val, 'val');
    if (!val) {
        selecList.value = [];
    }
}, { immediate: true, deep: true });

const warehouseList = ref<any[]>([]);


// 表格数据
const productList = ref<Product[]>([]);


const emit = defineEmits(['update:dialogVisible', 'submit']);

// 表单ref
const formRef = ref<FormInstance>();

// 表单验证规则
const rules = reactive<FormRules>({
    to_warehouse_name: [{ required: true, message: '请输入调入仓库', trigger: 'blur' }],
    transfer_date: [{ required: true, message: '请选择调拨日期', trigger: 'blur' }],
    note: [{ required: true, message: '请输入备注', trigger: 'blur' }],
});


const dialogTitle = computed(() => props.dialogType === 'add' ? '新增' : '编辑');


interface stock_transfer_items {
    product_no: string;
    product_name: string;
    specification: string;
    unit: string;
    from_warehouse_id: string;
    from_warehouse_name: string;
    stock_num: string | number;
    transfer_num: string | number;
    note: string;
}
// 表单数据
const formData = reactive({
    id: '',
    transfer_date: '',
    to_warehouse_id: '',
    to_warehouse_name: '',
    note: '',
    stock_transfer_items: [] as stock_transfer_items[]
});

// 监听对话框显示状态
const dialogVisible = computed({
    get: () => props.dialogVisible,
    set: (val) => {
        emit('update:dialogVisible', val);
    }
});

// 监听对话框打开
watch(() => dialogVisible.value, async (val) => {
    openDialog(val);

});

//打开弹窗调用
const openDialog = async (val: boolean, type?: string) => {
    if (val) {
        // 获取仓库列表
        try {
            const res = await api.publicFun.getWarehouseList({ type: 1 });
            if (res.code === 200) {
                warehouseList.value = res.data;
            }
        } catch (error) {
            console.error('获取仓库列表失败', error);
        }

        // 如果是编辑模式，加载数据
        if (props.dialogType === 'edit' && props.dialogRow.id) {
            loadTransferDetail(props.dialogRow.id, type);
        }
    } else {
        //清空表单数据
        Object.keys(formData).forEach(key => {
            formData[key] = '';
        });
        productList.value = [];
    }
}

const dbcpOpen = () => {
    // openDialog(true,'1');
    console.log(productList.value,'productList.value');
    
    if(productList.value.length > 0){
        selecList.value  =   productList.value
        console.log(selecList.value,'selecList.value');
    }
    showProductDialog.value = true;

}

// 加载拨调详情
async function loadTransferDetail(id: string, type?: string) {
    try {
        const res = await api.product.stock_transfer_detail({ id });
        if (res.code === 200) {
            // 填充表单数据
            Object.keys(formData).forEach(key => {
                if (res.data[key] !== undefined) {
                    formData[key] = res.data[key];
                }
            });
            productList.value = res.data.stock_transfer_items;

            // 填充产品列表并格式化为SelectProductDialog需要的数据结构
            if (res.data.stock_transfer_items && Array.isArray(res.data.stock_transfer_items)) {
                // 为SelectProductDialog准备数据
                selectedProducts.value = res.data.stock_transfer_items.map((item: any) => {
                    return {
                        id: item.product_id || item.id,
                        product: {
                            name: item.product_name,
                            no: item.product_no,
                            specification: item.specification,
                            unit: item.unit
                        },
                        stock_num: item.stock_num,
                        warehouse_id: item.from_warehouse_id,
                        transfer_num: item.transfer_num,
                        note: item.note
                    };
                });
            }

        }
    } catch (error) {
        console.error('获取拨调详情失败', error);
    }
}

// 删除产品
function removeProduct(index: number) {
    // 获取要删除的产品
    const removedProduct = productList.value[index];

    // 从产品列表中删除
    productList.value.splice(index, 1);

    // 同步更新selectedProducts，移除对应的产品
    selectedProducts.value = selectedProducts.value.filter(item =>
        !(item.id === removedProduct.id && item.warehouse_id === removedProduct.warehouse_id)
    );
}

function onWarehouseSelect(warehouse: any) {
    formData.to_warehouse_id = warehouse.id;
    formData.to_warehouse_name = warehouse.name;

}

const ShowClick = (type: string) => {
    showWarehouseDialog.value = true;
    if (type === '1') {
        formData.to_warehouse_id = '';
        formData.to_warehouse_name = '';
    }
}

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return;

    try {
        await formRef.value.validate();

        // 检查是否选择了产品
        if (productList.value.length === 0) {
            ElMessage.warning('请至少选择一个产品');
            return;
        }

        // 检查产品数量是否填写
        const invalidProduct = productList.value.find(item => !item.transfer_num);
        if (invalidProduct) {
            ElMessage.warning(`请填写产品"${invalidProduct.name}"的调拨数量`);
            return;
        }

        let dataArr

        if (props.dialogType === 'add') {
            dataArr = productList.value.map(item => {
                return {
                    product_no: item.no, // 产品SKU编号
                    product_name: item.name, // 产品名称
                    specification: item.specification, // 规格型号
                    unit: item.unit, // 拆零单位
                    from_warehouse_id: item.warehouse_id, // 来源仓库ID
                    from_warehouse_name: item.warehouse_name, // 来源仓库名称
                    stock_num: Number(item.stock_num).toFixed(2), // 来源仓库库存，保留两位小数
                    transfer_num: Number(item.transfer_num).toFixed(2), // 准备调拨的数量，保留两位小数
                    note: item.note // 备注
                }
            })
        } else {
            dataArr = productList.value.map(item => {
                console.log(item,'item');
                return {
                    product_no: item?.product_no || item?.no, // 产品SKU编号
                    product_name: item?.product_name || item?.name, // 产品名称
                    specification: item?.specification, // 规格型号
                    unit: item?.unit, // 拆零单位
                    from_warehouse_id: item?.from_warehouse_id || item?.warehouse_id, // 来源仓库ID
                    from_warehouse_name: item?.from_warehouse_name || item?.warehouse_name, // 来源仓库名称
                    note: item.note, // 备注
                    stock_num: Number(item.stock_num).toFixed(2), // 来源仓库库存，保留两位小数
                    transfer_num: Number(item.transfer_num).toFixed(2), // 准备调拨的数量，保留两位小数
                }
            })
        }
        formData.stock_transfer_items = dataArr;

        // 添加或编辑库存拨调
        if (props.dialogType === 'add') {
            const res = await api.product.stock_transfer_add(formData);
            if (res.code === 200) {
                ElMessage.success('添加成功');
                dialogVisible.value = false;
                emit('submit');
            } else {
                ElMessage.error(res.message || '添加失败');
            }
        }
        // 编辑库存拨调
        else if (props.dialogType === 'edit') {
            const res = await api.product.stock_transfer_edit(formData);
            if (res.code === 200) {
                ElMessage.success('更新成功');
                dialogVisible.value = false;
                emit('submit');
            } else {
                ElMessage.error(res.message || '更新失败');
            }
        }
    } catch (error) {

    }
};



</script>

<style lang="scss" scoped>
::v-deep .form-section {
    padding-top: 0px !important;
}

::v-deep .el-form-item__label {
    margin-left: 2px !important;
}

::v-deep .el-form-item__label-wrap {
    margin-left: 0px !important;
}

::v-deep .el-form-item {
    display: block;
    margin-bottom: 8px !important;
}


:deep(.el-dialog) {
    --el-dialog-padding-primary: 0px;
}

:deep(.el-dialog__header) {
    padding: 10px 16px;
    border-bottom: 1px solid #f0f0f0;
    font-weight: bold;
}

:deep(.dialog-footer) {
    padding: 10px 16px;
    border-top: 1px solid #f0f0f0;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
    color: #000;
}

:deep(.el-dialog__body) {
    padding: 20px 10px;
    padding-right: 30px;
}

.section-title {
    font-weight: bold;
    font-size: 16px;
    color: #222;
    margin: 24px 0 12px 0;


    // 添加左边元素  
    &::before {
        content: '';
        display: inline-block;
        width: 4px;
        height: 16px;
        background: #626aef;
        margin-right: 8px;
    }

}
</style>
